<template>
  <view class="home-page">
    <!-- 商户选择栏 -->
    <view class="store-header">
      <view class="store-selector" @click="onStoreSelect">
        <text class="store-icon">🏪</text>
        <text class="store-name">{{ currentStore.name || '请选择商户' }}</text>
        <text class="store-arrow">></text>
      </view>
    </view>

    <!-- 顶部搜索栏 -->
    <view class="search-header">
      <view class="search-bar">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          placeholder="搜索商品" 
          placeholder-class="placeholder"
          @focus="onSearchFocus"
        />
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-section">
      <swiper class="banner-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500" :circular="true">
        <swiper-item v-for="(item, index) in bannerList" :key="index">
          <view class="banner-item">
            <image class="banner-image" :src="item.image" mode="aspectFill"></image>
            <view class="banner-content">
              <view class="banner-text">
                <text class="banner-title">{{ item.title }}</text>
                <text class="banner-subtitle">{{ item.subtitle }}</text>
                <text class="banner-brand">{{ item.brand }}</text>
                <text class="banner-tag">{{ item.tag }}</text>
              </view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <!-- 限时抢购 -->
    <view class="rush-buy-section">
      <view class="section-header">
        <text class="section-title">限时抢购</text>
        <view class="countdown">
          <text class="countdown-label">距结束</text>
          <view class="countdown-time">
            <text class="time-item">{{ countdown.hours }}</text>
            <text class="time-separator">:</text>
            <text class="time-item">{{ countdown.minutes }}</text>
            <text class="time-separator">:</text>
            <text class="time-item">{{ countdown.seconds }}</text>
          </view>
        </view>
        <text class="more-link">更多 ></text>
      </view>
      
      <scroll-view class="rush-buy-list" scroll-x="true">
        <view class="rush-buy-item" v-for="(item, index) in rushBuyList" :key="index" @click="onProductClick(item)">
          <image class="rush-buy-image" :src="item.imageUrls ? item.imageUrls.split(',')[0] : defaultImage" mode="aspectFill"></image>
          <view class="rush-buy-info">
            <text class="rush-buy-price">¥{{ item.price || 10 }}</text>
            <!-- <text class="rush-buy-stock">仅剩{{ item.stock || 0 }}件</text> -->
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 排行榜 -->
    <view class="ranking-section">
      <view class="section-header">
        <text class="section-title">排行榜</text>
        <text class="more-link">更多 ></text>
      </view>
      
      <view class="ranking-card" @click="onRankingClick">
        <view class="ranking-content">
          <view class="ranking-text">
            <text class="ranking-subtitle">衣如其人/趣味穿搭</text>
            <text class="ranking-title">你是哪种水果穿搭?</text>
          </view>
          <image class="ranking-image" src="http://115.159.81.246:9000/supermarket/25624259A1B4E58588EE8569D0E53D0F.png" mode="aspectFill"></image>
        </view>
        <view class="ranking-button">
          <text class="button-text">立即抢购 ></text>
        </view>
      </view>
      
      <!-- 排行榜商品列表 -->
      <scroll-view class="ranking-list" scroll-x="true">
        <view class="ranking-item" v-for="(item, index) in rankingList" :key="index" @click="onProductClick(item)">
          <image class="ranking-item-image" :src="item.imageUrls ? item.imageUrls.split(',')[0] : defaultImage" mode="aspectFill"></image>
          <view class="ranking-item-info">
            <text class="ranking-item-price">¥{{ item.price || 0 }}</text>
            <text class="ranking-item-desc">{{ item.name || '商品名称' }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 人气推荐 -->
    <view class="popular-section">
      <view class="section-header">
        <text class="section-title">人气推荐</text>
        <text class="more-link">更多 ></text>
      </view>
      
      <!-- 人气推荐横幅 -->
      <view class="popular-banner">
        <image class="popular-banner-image" src="http://115.159.81.246:9000/supermarket/25624259A1B4E58588EE8569D0E53D0F.png" mode="aspectFill"></image>
      </view>
      
      <!-- 人气推荐商品列表 -->
      <scroll-view class="popular-list" scroll-x="true">
        <view class="popular-item" v-for="(item, index) in popularList" :key="index" @click="onProductClick(item)">
          <image class="popular-item-image" :src="item.imageUrls ? item.imageUrls.split(',')[0] : defaultImage" mode="aspectFill"></image>
          <view class="popular-item-info">
            <text class="popular-item-price">¥{{ item.price || 0 }}</text>
            <text class="popular-item-desc">{{ item.name || '商品名称' }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 为你推荐 -->
    <view class="recommend-section">
      <view class="section-header">
        <text class="section-title">为你推荐</text>
      </view>
      
      <view class="recommend-grid">
        <view class="recommend-item" v-for="(item, index) in recommendList" :key="index" @click="onProductClick(item)">
          <image class="recommend-item-image" :src="item.imageUrls ? item.imageUrls.split(',')[0] : defaultImage" mode="aspectFill"></image>
          <view class="recommend-item-info">
            <text class="recommend-item-title">{{ item.name || '商品名称' }}</text>
            <text class="recommend-item-price">¥{{ item.price || 0 }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>

</template>

<script>
import { get } from '@/utils/request.js'

export default {
  data() {
    return {
      currentStore: {
        id: null,
        name: '',
        address: ''
      },
      countdown: {
        hours: '02',
        minutes: '59',
        seconds: '48'
      },
      // 默认图片
      defaultImage: 'http://115.159.81.246:9000/supermarket/25624259A1B4E58588EE8569D0E53D0F.png',
      // 轮播图数据（保持不变）
      bannerList: [
        {
          image: 'http://115.159.81.246:9000/supermarket/e2120cf31753783963066.jpg',
          title: '25~49岁看过来',
          subtitle: '千元品质 百元价位',
          brand: 'BOMOVO高端女装',
          tag: '限时特价ing'
        },
        {
          image: 'http://115.159.81.246:9000/supermarket/e2120cf31753783963066.jpg',
          title: '春季新品上市',
          subtitle: '时尚潮流 引领风尚',
          brand: 'FASHION品牌',
          tag: '新品推荐'
        },
        {
          image: 'http://115.159.81.246:9000/supermarket/e2120cf31753783963066.jpg',
          title: '夏季清凉特惠',
          subtitle: '清爽舒适 美丽动人',
          brand: 'SUMMER系列',
          tag: '热销爆款'
        }
      ],
      // 动态商品数据
      rushBuyList: [], // 限时抢购：ID 130-134
      rankingList: [], // 排行榜：ID 135-137
      popularList: [], // 人气推荐：ID 138-140
      recommendList: [] // 为你推荐：ID 141-144
    }
  },

  onLoad() {
    this.loadStoreFromStorage()
    this.startCountdown()
    this.loadAllProductData()
  },

  onShow() {
    // 每次页面显示时重新加载商户信息，确保数据同步
    this.loadStoreFromStorage()
  },

  onUnload() {
    this.stopCountdown()
  },

  methods: {
    // 从Storage加载商户信息
    loadStoreFromStorage() {
      try {
        const selectedStore = uni.getStorageSync('selectedStore')
        if (selectedStore) {
          this.currentStore = {
            id: selectedStore.id,
            name: selectedStore.name,
            address: selectedStore.address || ''
          }
        } else {
          // 如果没有选择商户，显示默认状态
          this.currentStore = {
            id: null,
            name: '请选择商户',
            address: ''
          }
        }
      } catch (error) {
        console.error('加载商户信息失败:', error)
        this.currentStore = {
          id: null,
          name: '请选择商户',
          address: ''
        }
      }
    },

    // 加载所有商品数据
    async loadAllProductData() {
      try {
        // 并行加载所有商品数据
        await Promise.all([
          this.loadRushBuyProducts(), // 限时抢购：ID 130-134
          this.loadRankingProducts(), // 排行榜：ID 135-137
          this.loadPopularProducts(), // 人气推荐：ID 138-140
          this.loadRecommendProducts() // 为你推荐：ID 141-144
        ])
      } catch (error) {
        console.error('加载商品数据失败:', error)
        uni.showToast({
          title: '加载商品数据失败',
          icon: 'none'
        })
      }
    },

    // 加载限时抢购商品（ID 130-134）
    async loadRushBuyProducts() {
      try {
        const response = await get('/transaction/SpuWithPrice/range', {
          startId: 130,
          endId: 134
        })
        
        if (response.code === 200) {
          this.rushBuyList = response.data || []
          console.log('限时抢购商品加载成功:', this.rushBuyList)
        } else {
          console.error('加载限时抢购商品失败:', response.msg)
        }
      } catch (error) {
        console.error('请求限时抢购商品失败:', error)
      }
    },

    // 加载排行榜商品（ID 135-137）
    async loadRankingProducts() {
      try {
        const response = await get('/transaction/SpuWithPrice/range', {
          startId: 135,
          endId: 137
        })
        
        if (response.code === 200) {
          this.rankingList = response.data || []
          console.log('排行榜商品加载成功:', this.rankingList)
        } else {
          console.error('加载排行榜商品失败:', response.msg)
        }
      } catch (error) {
        console.error('请求排行榜商品失败:', error)
      }
    },

    // 加载人气推荐商品（ID 138-140）
    async loadPopularProducts() {
      try {
        const response = await get('/transaction/SpuWithPrice/range', {
          startId: 138,
          endId: 140
        })
        
        if (response.code === 200) {
          this.popularList = response.data || []
          console.log('人气推荐商品加载成功:', this.popularList)
        } else {
          console.error('加载人气推荐商品失败:', response.msg)
        }
      } catch (error) {
        console.error('请求人气推荐商品失败:', error)
      }
    },

    // 加载为你推荐商品（ID 141-144）
    async loadRecommendProducts() {
      try {
        const response = await get('/transaction/SpuWithPrice/range', {
          startId: 141,
          endId: 144
        })
        
        if (response.code === 200) {
          this.recommendList = response.data || []
          console.log('为你推荐商品加载成功:', this.recommendList)
        } else {
          console.error('加载为你推荐商品失败:', response.msg)
        }
      } catch (error) {
        console.error('请求为你推荐商品失败:', error)
      }
    },

    // 门店选择
    onStoreSelect() {
      uni.navigateTo({
        url: '/pages/select_store/select_store'
      })
    },

    // 搜索框获得焦点
    onSearchFocus() {
      uni.navigateTo({
        url: '/pages/category/search/search'
      })
    },

    // 点击商品
    onProductClick(product) {
      console.log('点击商品:', product)
      uni.navigateTo({
        url: `/pages/product-detail/product-detail?id=${product.id}`
      })
    },

    // 点击排行榜
    onRankingClick() {
      console.log('点击排行榜')
      uni.navigateTo({
        url: '/pages/ranking/ranking'
      })
    },

    // 开始倒计时
    startCountdown() {
      this.countdownTimer = setInterval(() => {
        let hours = parseInt(this.countdown.hours)
        let minutes = parseInt(this.countdown.minutes)
        let seconds = parseInt(this.countdown.seconds)
        
        seconds--
        
        if (seconds < 0) {
          seconds = 59
          minutes--
          
          if (minutes < 0) {
            minutes = 59
            hours--
            
            if (hours < 0) {
              // 倒计时结束，重置
              hours = 2
              minutes = 59
              seconds = 48
            }
          }
        }
        
        this.countdown.hours = hours.toString().padStart(2, '0')
        this.countdown.minutes = minutes.toString().padStart(2, '0')
        this.countdown.seconds = seconds.toString().padStart(2, '0')
      }, 1000)
    },

    // 停止倒计时
    stopCountdown() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
      }
    }
  }
}
</script>

<style scoped>
.home-page {
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 门店选择栏 */
.store-header {
  background-color:#ff4757;
  padding: 15rpx 30rpx;
  border-bottom: 0rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.store-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 50%;
  background-color: #f8f8f8;
  padding: 8rpx 15rpx;
  border-radius: 15rpx;
}

.store-icon {
  font-size: 24rpx;
  margin-right: 10rpx;
}

.store-name {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.store-arrow {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

/* 顶部搜索栏 */
.search-header {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  padding: 0rpx 30rpx 200rpx; /* 增加底部padding，让红色背景延伸到轮播图一半 */
}

.search-bar {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 25rpx;
  padding: 20rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.search-icon {
  font-size: 32rpx;
  color: #999;
  margin-right: 20rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.placeholder {
  color: #999;
  font-size: 28rpx;
}

/* 轮播图 */
.banner-section {
  margin: -120rpx 30rpx 20rpx; /* 负margin让轮播图向上移动，与红色背景重叠 */
}

.banner-swiper {
  height: 300rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
}

.banner-item {
  position: relative;
  width: 100%;
  height: 100%;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.banner-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, rgba(0, 0, 0, 0.3) 0%, transparent 100%);
  display: flex;
  align-items: center;
  padding: 40rpx;
}

.banner-text {
  color: #fff;
  max-width: 60%;
}

.banner-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  line-height: 1.2;
}

.banner-subtitle {
  display: block;
  font-size: 28rpx;
  margin-bottom: 8rpx;
  opacity: 0.9;
}

.banner-brand {
  display: block;
  font-size: 24rpx;
  margin-bottom: 6rpx;
  opacity: 0.8;
}

.banner-tag {
  display: block;
  font-size: 22rpx;
  opacity: 0.7;
}

/* 限时抢购 */
.rush-buy-section {
  margin: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.countdown {
  display: flex;
  align-items: center;
}

.countdown-label {
  font-size: 24rpx;
  color: #666;
  margin-right: 15rpx;
}

.countdown-time {
  display: flex;
  align-items: center;
}

.time-item {
  background-color: #ff4757;
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
  padding: 8rpx 12rpx;
  border-radius: 6rpx;
  min-width: 40rpx;
  text-align: center;
}

.time-separator {
  font-size: 24rpx;
  color: #ff4757;
  font-weight: bold;
  margin: 0 8rpx;
}

.more-link {
  font-size: 26rpx;
  color: #999;
}

.rush-buy-list {
  white-space: nowrap;
}

.rush-buy-item {
  display: inline-block;
  width: 200rpx;
  margin-right: 20rpx;
  transition: all 0.3s ease;
}

.rush-buy-item:active {
  transform: scale(0.95);
}

.rush-buy-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  margin-bottom: 15rpx;
}

.rush-buy-info {
  text-align: center;
}

.rush-buy-price {
  display: block;
  font-size: 28rpx;
  color: #ff4757;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.rush-buy-stock {
  display: block;
  font-size: 22rpx;
  color: #999;
}

/* 排行榜 */
.ranking-section {
  margin: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.ranking-card {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 16rpx;
  padding: 30rpx;
  transition: all 0.3s ease;
}

.ranking-card:active {
  transform: scale(0.98);
}

.ranking-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.ranking-text {
  flex: 1;
  margin-right: 30rpx;
}

.ranking-subtitle {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.ranking-title {
  display: block;
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  line-height: 1.3;
}

.ranking-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  flex-shrink: 0;
}

.ranking-button {
  margin-top: 20rpx;
  text-align: center;
}

.button-text {
  background-color: #ff4757;
  color: #fff;
  font-size: 26rpx;
  padding: 15rpx 30rpx;
  border-radius: 25rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 71, 87, 0.3);
}

/* 排行榜商品列表 */
.ranking-list {
  white-space: nowrap;
  margin-top: 20rpx;
}

.ranking-item {
  display: inline-block;
  width: 200rpx;
  margin-right: 20rpx;
  transition: all 0.3s ease;
}

.ranking-item:active {
  transform: scale(0.95);
}

.ranking-item-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  margin-bottom: 15rpx;
}

.ranking-item-info {
  text-align: center;
}

.ranking-item-price {
  display: block;
  font-size: 28rpx;
  color: #ff4757;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.ranking-item-desc {
  display: block;
  font-size: 22rpx;
  color: #666;
  line-height: 1.3;
}

/* 人气推荐 */
.popular-section {
  margin: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.popular-banner {
  margin-bottom: 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.popular-banner-image {
  width: 100%;
  height: 200rpx;
}

.popular-list {
  white-space: nowrap;
}

.popular-item {
  display: inline-block;
  width: 200rpx;
  margin-right: 20rpx;
  transition: all 0.3s ease;
}

.popular-item:active {
  transform: scale(0.95);
}

.popular-item-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  margin-bottom: 15rpx;
}

.popular-item-info {
  text-align: center;
}

.popular-item-price {
  display: block;
  font-size: 28rpx;
  color: #ff4757;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.popular-item-desc {
  display: block;
  font-size: 22rpx;
  color: #666;
  line-height: 1.3;
}

/* 为你推荐 */
.recommend-section {
  margin: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.recommend-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;
}

.recommend-item {
  transition: all 0.3s ease;
}

.recommend-item:active {
  transform: scale(0.95);
}

.recommend-item-image {
  width: 100%;
  height: 300rpx;
  border-radius: 12rpx;
  margin-bottom: 15rpx;
}

.recommend-item-info {
  text-align: center;
}

.recommend-item-title {
  display: block;
  font-size: 26rpx;
  color: #333;
  line-height: 1.3;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.recommend-item-price {
  display: block;
  font-size: 28rpx;
  color: #ff4757;
  font-weight: bold;
}

/* 轮播图指示器样式 */
.banner-swiper .uni-swiper-dots {
  bottom: 20rpx;
}

.banner-swiper .uni-swiper-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 8rpx;
  background-color: rgba(255, 255, 255, 0.5);
  margin: 0 8rpx;
}

.banner-swiper .uni-swiper-dot-active {
  background-color: #fff;
}
</style>